// app.js
App({
  onLaunch() {
  //   // 展示本地存储能力
  //   const logs = wx.getStorageSync('logs') || []
  //   logs.unshift(Date.now())
  //   wx.setStorageSync('logs', logs)

  //   // 登录
  //   wx.login({
  //     success: res => {
  //       // 发送 res.code 到后台换取 openId, sessionKey, unionId
  //     }
  //   })

    this.globalData = {
      userInfo: null,
      baseUrl: 'http://192.168.43.135:8000/api', // 替换为Django服务器地址
			mqttClient: null,
      mqttConnected: false,
      deviceOnline: false,
      waterLevelWarning: false,
      isLoggedIn: false,
			hasSubscribed: false
    };

		// 尝试从本地存储恢复登录状态
    const userInfo = wx.getStorageSync('userInfo');
    if (userInfo) {
      this.globalData.isLoggedIn = true;
    }
  },

	// 全局方法：设置MQTT客户端
  setMqttClient(client) {
    this.globalData.mqttClient = client;
  },

	// 全局方法：更新MQTT状态
  updateMqttStatus(connected, online, warning) {
    this.globalData.mqttConnected = connected;
    this.globalData.deviceOnline = online;
    this.globalData.waterLevelWarning = warning;

    // 通知所有页面更新
    this.notifyPages();
  },

  // 全局方法：更新登录状态
  updateLoginStatus(loggedIn) {
    this.globalData.isLoggedIn = loggedIn;

		if (loggedIn) {
      wx.setStorageSync('userInfo');
    } else {
      wx.removeStorageSync('userInfo');
    }

    // 通知所有页面更新
    this.notifyPages();
  },

	// 全局方法：更新订阅状态
  updateSubscribeStatus(hasSubscribed) {
    this.globalData.hasSubscribed = hasSubscribed;

    // 通知所有页面更新
    this.notifyPages();
  },

  // 通知所有页面更新数据
	notifyPages() {
		const pages = getCurrentPages();
		pages.forEach(page => {
			if (page.onGlobalDataUpdate) {
				page.onGlobalDataUpdate();
			}
		});
	},

	GlobalonSendMessageTest(){
		// 检查两个前提条件
		if (!this.globalData.isLoggedIn) {
			wx.showToast({
				title: '请先登录',
				icon: 'none',
				duration: 2000
			});
			return;
		}
		if (!this.globalData.hasSubscribed) {
			wx.showToast({
				title: '请先同意订阅消息',
				icon: 'none',
				duration: 2000
			});
			return;
		}
			// 在用户同意订阅后，调用服务端发送测试消息
			wx.request({
				url: this.globalData.baseUrl + '/wechat/send-subscribe-message/',
				method: 'POST',
				data: {
					openid: wx.getStorageSync('openid'),
					template_id: 'PU_crKS9E8O6rjC_4wtmbYPqkTR-S2ew0u0NmLtxxg8',
				// page:
					data: {
						"thing1": {"value": "家"},
						"thing2": {"value": "水位高报警"},
						// "time3": {"value": "2024-01-15 14:30"}
						"time3": {
							"value": (() => {
								const now = new Date();
								return `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-${String(now.getDate()).padStart(2, '0')} ${String(now.getHours()).padStart(2, '0')}:${String(now.getMinutes()).padStart(2, '0')}`;
							})()
						}
					}
			},
			success: (msgResult) => {
				console.log('消息发送request结果:', msgResult.data)
			},
			fail: (err) => {
				console.error('消息发送request失败:', err);
			}
		}) // end of wx.request({
	}, // end of onSendMessageTest()
})
